package com.czf.testmodule.time.timer;

import cn.hutool.core.date.DateTime;
import lombok.extern.slf4j.Slf4j;

import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author zfChen
 * @create 2022/6/7 10:07
 */
@Slf4j
public class ScheduledThreadPoolExecutorDemo {
    public static void main(String[] args) {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                log.debug("当前时间{}线程名称{}", DateTime.now(), Thread.currentThread().getName());
            }
        };

        log.info("当前的时间{}线程名称{}", DateTime.now(), Thread.currentThread().getName());
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(3);
        executorService.scheduleAtFixedRate(task,2000,2000, TimeUnit.MILLISECONDS);
        // 2秒后，每隔2秒，执行一次任务
        log.info("sleep"+DateTime.now());
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("After"+DateTime.now());
        executorService.shutdown(); //停止执行任务
    }
}
